package com.cyan.tools.util;


import com.cyan.tools.bean.BodyResponse;
import com.cyan.tools.bean.Result;
import com.cyan.tools.callback.RequestCallback;
import com.cyan.tools.handler.ErrorHandler;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;


/**
 * Created by pc on 2017/3/10.
 */

public class SimpleSubscriber<T> implements Observer<T> {
    private RequestCallback requestCallback;
    private Disposable mDisposable;

    public SimpleSubscriber(RequestCallback requestCallback) {
        this.requestCallback = requestCallback;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        requestCallback.beforeRequest();
        mDisposable = d;
    }

    @Override
    public void onComplete() {
        requestCallback.requestComplete();
        mDisposable.dispose();
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof HttpException) {
            BodyResponse bodyResponse = ErrorHandler.handle(e);
            if (((HttpException) e).message() != null && ((HttpException) e).message().equals("Unauthorized")) {
                requestCallback.requestError("验证过期");
                RxBus.get().post("logout", "logout");
                return;
            }
            if (bodyResponse != null) {
                requestCallback.requestError(bodyResponse.getMessage());
                return;
            }
        }
        requestCallback.requestError("网络错误");
        mDisposable.dispose();
    }

    @Override
    public void onNext(T o) {
        if (o instanceof Result)
            requestCallback.requestSuccess(((Result) o).getData());
        else requestCallback.requestSuccess(o);
    }
}
